
package com.lwl.reference;

import java.lang.ref.SoftReference;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SoftReferenceDemo {

	//private static ReferenceQueue<MyObject> queue = new ReferenceQueue<>();

	private static ConcurrentHashMap<String,SoftReference<String>> map = new ConcurrentHashMap<>(1000);

	public static void main(String[] args) throws InterruptedException {

		System.out.println("开始运行");
		for (int i = 0; i < 1000; i++) {
			map.put("aaa"+i,new SoftReference<>(new String("hello")));
			//hashMap.put("aaa"+i,new SoftReference<String>("hello"));
			System.gc();
			Thread.sleep(20);
			System.out.println(i);
		}

		Iterator<Map.Entry<String, SoftReference<String>>> iterator = map.entrySet().iterator();
		while (iterator.hasNext()){
			Map.Entry<String, SoftReference<String>> next = iterator.next();
			SoftReference<String> value = next.getValue();
			String s = value.get();
			if (s == null){
				iterator.remove();
			}
			System.out.println(s);
		}
		System.out.println("运行结束,Map剩余长度为"+map.size());
	}

}
